<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { ethers } from "ethers";
import { ElMessage, ElNotification } from "element-plus";
import Operation from './Operation.vue'

const account = ref<string | undefined>(localStorage.getItem("account") || "");
const chainId = ref<string | undefined>(localStorage.getItem("chainId") || "");
const ethereum = (window as any).ethereum;
const connectWallet = async () => {
  try {
    if (!ethereum) {
      console.log("-------------", ethers.getDefaultProvider())
      ElNotification({
        title: "提示",
        message: "请先安装浏览器插件 Metamask",
        type: "warning",
      });
      return
    }

    const provider = new ethers.BrowserProvider(ethereum) // 获取提供者
    const signer = await provider.getSigner() // 获取钱包签名
    account.value = await signer.getAddress() // 获取钱包地址
    // const myAccounts = await provider.send("eth_requestAccounts", [])
    // console.log("相关信息", provider, signer, myAccounts)
    const network = await provider.getNetwork()
    chainId.value = network.chainId.toString()
    // 保存相关信息到本地
    localStorage.setItem("chainId", chainId.value)
    localStorage.setItem("account", account.value)
    ElMessage.success("连接钱包成功")
  } catch (error) {
    console.log('连接钱包失败：', error)
  }
}

const disconnectWallet = async () => {
  if (localStorage.getItem("account")) {
    account.value = ""
    localStorage.removeItem("account")
    ElMessage.warning("断开钱包成功")
  }
}
onMounted(() => {
  // 由于 TypeScript 类型检查中 window 对象默认没有 ethereum 属性，使用类型断言解决该问题
  if (ethereum) {
    // 使用类型断言解决 TypeScript 类型检查中 window 对象没有 ethereum 属性的问题
    ethereum.on("accountsChanged", (accounts: string[]) => {
      // 钱包账户变化
      console.log("钱包账户变化", accounts[0]);
      account.value = accounts[0];
      localStorage.setItem("account", accounts[0]);
    });
    ethereum.on("chainChanged", (chainId: string) => {
      // 切换网络
      console.log("切换网络", chainId);
      localStorage.setItem("chainId", chainId.toString());
    });
  } else {
    ElNotification({
      title: "Error",
      message: "请安装 Metamask 钱包",
      type: "error",
      duration: 3000,
    });
  }
});
</script>

<template>
  <div class="wallet">
    <div v-if="!account" class="wallet-login">
      <h3>连接 Metamask 钱包</h3>
      <el-button type="primary" @click="connectWallet" size="large"
        >连接钱包</el-button
      >
    </div>
    <div v-else>
      <el-button type="danger" @click="disconnectWallet">断开钱包</el-button>
      <p>钱包地址：{{ account }}</p>
      <p>链ID：{{ chainId }}</p>
      <Operation />
    </div>
  </div>
</template>

<style scoped>
.wallet {
  width: 1000px;
}
</style>
